/*
 * Copyright (c) 2021 com.youkeyi. All rights reserved.
 *
 *  @author liuxiawang
 *  @location Shenzhen.China
 *  @date 4/10/21 12:40 AM
 */

package com.youkeyi.ddy.cloud.common.config;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootVersion;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.RequestParameterBuilder;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.ParameterType;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.Collections;

/**
 * 各个服务的Swagger配置
 *
 * @Author liuxiawang
 * @Date 2021-04-10 23:39
 * @Location shenzhen.china
 */
@EnableOpenApi
@Configuration
@Component
public class SwaggerConfig implements OperationBuilderPlugin {

    private static final Logger logger = LoggerFactory.getLogger(SwaggerConfig.class);

    @Value("${spring.application.name}")
    private String applicationName;
    @Value("${swagger.base.package:demo}")
    private String swaggerBasePackage;

    @Bean
    public Docket createRestApi() {
        // 要拼接成服务的根包路径，如 com.youkeyi.demo
        String basePackage = String.format("com.youkeyi.ddy.cloud.%s", swaggerBasePackage);

        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                // .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                .paths(PathSelectors.any())
                .build()
                .globalRequestParameters(
                         Collections.singletonList(
                                 new RequestParameterBuilder()
                                         .name("Token")
                                         .description("Token")
                                         .in(ParameterType.HEADER)
                                         .required(true)
                                         .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
                                         .build()
                         )
                );


    }

    /**
     * API 页面上半部分展示信息
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title(applicationName + " API DOC")
                .description(String.format("Youkeyi %s的API文档", applicationName))
                .contact(new Contact("YOUKEYI", "www.youkeyi.com", "584595327@qq.com"))
                .termsOfServiceUrl("")
                .version("Application Version: v1, Spring Boot Version: " + SpringBootVersion.getVersion())
                .build();
    }

    @Override
    public boolean supports(DocumentationType delimiter) {
        return true;
    }

    @Override
    public void apply(OperationContext context) {
//        List<ApiOperation> annotations = context.findAllAnnotations(ApiOperation.class);
//        if (CollectionUtils.isNotEmpty(annotations)) {
//            // List<Map<String, String>> interfaceAuthMapList = new ArrayList<>();
//            for (ApiOperation op : annotations) {
//                Map<String, String> interfaceAuthMap = new HashMap<>();
//                interfaceAuthMap.put("primaryKey", SimpleUUidUtils.getUuid());
//                interfaceAuthMap.put("serviceName", applicationName);
//                interfaceAuthMap.put("interfaceName", String.format("%s-%s-%s", op.value(), op.notes(), JSON.toJSONString(op.tags())));
//                Authorization[] authorizations = op.authorizations();
//                if (authorizations.length > 0) {
//                    Authorization authorization = authorizations[0];
//                    try {
//                        String auth = SecurityUtils.encryptText(authorization.value(), "123!@#qweQWE");
//                        interfaceAuthMap.put("primaryKey", auth);
//                        interfaceAuthMap.put("package", authorization.value());
//                        context.operationBuilder().notes(String.format("接口权限KEY： %s", auth));
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//                // interfaceAuthMapList.add(interfaceAuthMap);
//
//                // 1。调用权限服务，将本服务内的权限根据key进行save or update
//                String sql = "INSERT INTO `youkeyi_cloud_uas`.`sys_api_auth` (`primary_key`, `auth_type`, `auth_name`, `auth_code`, `api_url`) VALUES ('%s', '%s', '%s', '%s', '%s');";
//                System.err.println(
//                        String.format(
//                                sql,
//                                interfaceAuthMap.get("primaryKey"),
//                                interfaceAuthMap.get("serviceName"),
//                                op.value(),
//                                interfaceAuthMap.get("primaryKey"),
//                                interfaceAuthMap.get("package")
//                        )
//                );
//            }
//            // logger.info("扫描到的需要设置权限的接口有 {} 个，内容为 {}", interfaceAuthMapList.size(), JSON.toJSONString(interfaceAuthMapList));
//        }
    }
}
